//
//  MainVC.m
//  TST
//
//  Created by POP3mac on 2020/4/27.
//  Copyright © 2020 YTYanK. All rights reserved.
//

#import "MainVC.h"
#import "TSTClockPage.h"
#import "TSTCalendarPage.h"
#import "AppDelegate.h"

@interface MainVC ()

@end

@implementation MainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setAllInitSubView];
    [self setAllSubViewLayout];
    [self updateAllData];
    // Do any additional setup after loading the view.
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES];
}


- (void)setAllInitSubView {
    self.title = @"首頁";
    self.logoIcon =  [[UIImageView alloc] initWithFrame:CGRectZero];
     self.logoIcon.hidden  =YES;
    self.logoIcon.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.logoIcon];
    
    self.textView = [[UILabel alloc] initWithFrame:CGRectZero];
    self.textView.numberOfLines = 1;
//    self.textView.backgroundColor =  UIColor.yellowColor;
    self.textView.hidden  =YES;
    self.textView.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.textView];
    
    self.calendar  = [UIButton buttonWithType:UIButtonTypeCustom];
    self.calendar.backgroundColor = YTYRGB_RANDOM;
    [self.calendar setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
     [self.calendar setViewBorderCornerRadius:6 borderWidth:0 borderColor:UIColor.clearColor];
    [self.calendar addTarget:self action:@selector(calendarClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.calendar];
    
    
    self.punchClock = [UIButton buttonWithType:UIButtonTypeCustom];
    self.punchClock.backgroundColor =  YTYRGB(0, 107, 95);
    [self.punchClock setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.punchClock setViewBorderCornerRadius:6 borderWidth:0 borderColor:UIColor.clearColor];
    [self.punchClock addTarget:self action:@selector(punchClockClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.punchClock];
    
    
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager =[[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 10.0;
        [_locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }else {
        [MBProgressHUD  showError:@"當前訊號弱，無法獲取定位"];
    }

    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
           button.frame =CGRectMake(-45, 0, 45, 45);
           button.imageEdgeInsets =  UIEdgeInsetsMake(0, 0, 0, 20);
          [button setTitle:@"登出" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(logoutClick) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:UIColor.blueColor forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [YTYTools obtainItemWithCustomView:button];
}
- (void)setAllSubViewLayout {
    [self.logoIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(SCREEN_NAV_BAR);
        make.centerX.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(100);
        make.width.mas_equalTo(100);
    }];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(self.logoIcon.mas_bottom).with.offset(25);
           make.centerX.equalTo(self.view).with.offset(0);
           make.height.mas_equalTo(30);
           make.width.mas_equalTo(SCREEN_WIDTH);
       }];
    
    CGFloat aveW  =  (SCREEN_WIDTH - 60 - 40)/2;
    
    [self.calendar mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(self.textView.mas_bottom).with.offset(15);
           make.left.equalTo(self.view).with.offset(30);
           make.height.mas_equalTo(aveW);
           make.width.mas_equalTo(aveW);
    }];
    
    [self.punchClock mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(self.textView.mas_bottom).with.offset(15);
           make.left.equalTo(self.calendar.mas_right).with.offset(40);
           make.height.mas_equalTo(aveW);
           make.width.mas_equalTo(aveW);
    }];
    
//   [self.logoIcon mas]
}
- (void)updateAllData {

    self.textView.text = @"textView";
    [self.calendar setTitle:@"日程表" forState:UIControlStateNormal];
    [self.punchClock setTitle:@"打卡" forState:UIControlStateNormal];
}
//- (IBAction)logoutClick:(UIBarButtonItem *)sender {
//    [AppDelegate logout];
//}

- (void)logoutClick {
    [AppDelegate logout];
}

- (void)calendarClick:(UIButton *)sender {
    NSLog(@"--》%@",[TSTApi sharedTSTApi].userModel.staff_id);
     if([TSTApi sharedTSTApi].userModel.staff_id == nil) {
         [MBProgressHUD showError:@"獲取用戶訊息失敗，無法使用日程表功能!"];
     }else {
         [self performSegueWithIdentifier:@"goCalendarPage" sender:nil];
     }
    
}

- (void)punchClockClick:(UIButton *)sender {
    if([TSTApi sharedTSTApi].userModel.staff_id == nil) {
           [MBProgressHUD showError:@"獲取用戶訊息失敗，無法使用打卡功能!"];
       }else {
           [self performSegueWithIdentifier:@"goClockPage" sender:nil];
       }
    
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([[segue identifier] isEqualToString:@"goCalendarPage"]){
             TSTCalendarPage *cap = (TSTCalendarPage *)[segue destinationViewController];
        cap.title = @"日程表";
    }else { //goClockPage
      
        
        [TSTApi requestWithUrl:AUIsClock parameters:@{@"staff_id": [TSTApi sharedTSTApi].userModel.staff_id} method:NetMethodGET returnModel:^(id  _Nonnull model) {
            TSTClockPage *clp = (TSTClockPage *)[segue destinationViewController];
               clp.title = @"打卡";
               clp.isClock = [model[@"is_clock"] boolValue];
               clp.lon = self.position.longitude;
               clp.lat = self.position.latitude;
         }];
        
        
    }
  //  [segue perform];
}

#pragma  mark - CLLocationManagerDelegate
//定位成功ocationManager:didUpdateLocations
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = locations.lastObject;
    // 经纬度
    self.position = location.coordinate;
    // 当前个人定位的经纬度 //-x:37.785834---y:-122.406417
    NSLog(@"经纬度---->%f-->%f",self.position.latitude,self.position.longitude);
    [manager stopUpdatingLocation]; //停止定位
}
//定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
//    NSLog(@"------>>err-->?%@",manager);
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"允許\"定位\"提示" message:@"請在設置中打開定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打開定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];
    [alertVc addAction:cancel];
    [alertVc addAction:ok];
    [self presentViewController:alertVc animated:YES completion:nil];
    
    // 隔15s 重新开启定位?
}

@end
